#include "mycustomplot.h"

MyCustomPlot::MyCustomPlot(QWidget *parent) : QCustomPlot(parent),isDragging(false)
{

    connect(this,&QCustomPlot::mouseMove,this,&MyCustomPlot::onMouseMoved);
    connect(this,&QCustomPlot::mousePress,this,&MyCustomPlot::onMousePree);

    vecFreq.clear();
    vecLev.clear();

    setMouseTracking(false);

    file.setFileName("./config/orig.csv");

    if(file.open(QFile::ReadOnly))
    {
        QTextStream ts(&file);
        while (!ts.atEnd())
        {
            QStringList readAll =  ts.readLine().split(",");
            if(readAll.size() > 1)
            {
                vecFreq.append(readAll.first().toFloat());
                vecLev.append(readAll.back().toFloat());
            }
        }
    }


    MaxVec = findPeaks(vecLev,10);


    if(MaxVec.size() > 0)
    {
        qDebug() << "Freq = " << QString::number(vecFreq[MaxVec[0]],'f') << "Lev = " << vecLev[MaxVec[0]] ;
        qDebug() << "Freq = " << QString::number(vecFreq[MaxVec[1]],'f') << "Lev = " << vecLev[MaxVec[1]] ;
    }




    this->addGraph();
    AxisTicker = new MyAxisTicker();
    axisRect()->setAutoMargins(QCP::msNone);
    axisRect()->setMargins(QMargins(40,1,1,1));
    setBackground(Qt::black);
    QSharedPointer<QCPAxisTicker> aaa(new QCPAxisTicker);
    aaa->setTickCount(10);

    xAxis->setTicker(aaa);
    xAxis->setTicks(false);
    xAxis->setTickLabels(false);
    xAxis->setBasePen(QPen(Qt::white));
    xAxis->grid()->setPen(QPen(Qt::white));
    xAxis->setPadding(1);
    xAxis->setRange(vecFreq.first(),vecFreq.last());

    AxisTicker->setTickCount(10);
    yAxis->setTicker(QSharedPointer<QCPAxisTicker>(AxisTicker));
    yAxis->setBasePen(QPen(Qt::white));
    yAxis->setSubTicks(true);
    yAxis->grid()->setPen(QPen(Qt::white));
    yAxis->grid()->setSubGridPen(QPen(QColor(128,128,128),1,Qt::DashLine));
    yAxis->grid()->setSubGridVisible(false);
    yAxis->setTickLabels(true);
    yAxis->setTickLabelColor(Qt::white);
    yAxis->setScaleType(QCPAxis::stLinear);
    yAxis->setTickLabelSide(QCPAxis::lsOutside);
    yAxis->setRange(0-100,0);

    this->graph(0)->addData(vecFreq,vecLev);
    this->graph(0)->setPen(QPen(Qt::yellow));

//    textLable = new QCPItemText(this);
//    textLable->setTextAlignment(Qt::AlignVCenter);
//    textLable->position->setType(QCPItemPosition::ptAxisRectRatio);
//    textLable->setPen(Qt::NoPen);
//    textLable->setFont(QFont(this->font().family(),14));
//    textLable->setText("M1");
//    textLable->setColor(Qt::white);
//    textLable->setVisible(false);


    textLableShow = new QCPItemText(this);
    textLableShow->setTextAlignment(Qt::AlignTop | Qt::AlignLeft);
    textLableShow->position->setType(QCPItemPosition::ptAxisRectRatio);
    textLableShow->setPen(QPen(Qt::red));
    textLableShow->setFont(QFont(this->font().family(),18));
    textLableShow->setColor(Qt::white);
    textLableShow->position->setCoords(0.90,0.05);
    textLableShow->setPadding(QMargins(5,5,5,5));
    textLableShow->setText("");
    textLableShow->setVisible(false);

    tracer = new QCPItemTracer(this);
    tracer->setGraph(this->graph());
    tracer->setPen(QPen(Qt::white,2));
    tracer->setBrush(QBrush(Qt::white));
    tracer->setStyle(QCPItemTracer::tsSquare);
    tracer->setInterpolating(true);
    tracer->setVisible(false);
	//本地第一次创建
    //sdashdajsjdakjsdhkahjshdjaksdjaksjd
    this->replot();
}

QVector<size_t> MyCustomPlot::findPeaks(const QVector<double> &src, int distance)
{
    size_t length=src.size();
    if(length<=1) return QVector<size_t>();
    QVector<int> sign(length,-1);
    QVector<double> difference(length,0);
    QVector<size_t> temp_out;
    std::adjacent_difference(src.begin(),src.end(),difference.begin());
    difference.removeFirst();
    difference.removeLast();
    for (int i = 0; i < difference.size(); ++i) {
        if(difference[i]>=0) sign[i]=1;
    }
    for (size_t j = 1; j < length-1; ++j)
    {
        int  diff = sign[j] - sign[j - 1];
        if (diff < 0) {
            temp_out.push_back(j);
        }
    }
    if(temp_out.size()==0 || distance==0 ) return temp_out;
    std::sort(temp_out.begin(),temp_out.end(),[&src](size_t a,size_t b){
        return (src[a]>src[b]);
    });

    QVector<size_t> ans;
    QHash<size_t ,int> except;
    for (auto it:temp_out) {
        if(!except.count(it))//如果不在排除范围内
        {
            ans.push_back(it);
            //更新
            size_t left=it-distance>0? it-distance:0;
            size_t right=it+distance>length-1? length-1:it+distance;
            for(size_t i=left;i<=right;++i)
                ++except[i];
        }
    }

    return ans;
}

void MyCustomPlot::setMarkerShow(bool Std)
{
    isDragging = Std;
    if(!isDragging)
    {
        textLableShow->setVisible(false);
        tracer->setVisible(false);
        this->replot();
    }else
    {

        textLableShow->setVisible(true);
        tracer->setTracerText("M2");
        tracer->setVisible(true);
        tracer->setGraphKey(vecFreq[MaxVec[0]]);
        tracer->updatePosition();
        double tracerX = tracer->position->key();
        double tracerY = tracer->position->value();
        textLableShow->setText(QString("频率：%1\n幅值：%2").arg(QString::number(tracerX,'f')).arg(tracerY));
        this->replot();



    }
    
}

void MyCustomPlot::setMarkVal(QString val)
{
    tracer->setGraphKey(val.toDouble());
    tracer->updatePosition();
    double tracerX = tracer->position->key();
    double tracerY = tracer->position->value();
    textLableShow->setText(QString("频率：%1\n幅值：%2").arg(QString::number(tracerX,'f')).arg(tracerY));
    this->replot();
}

void MyCustomPlot::onMouseMoved(QMouseEvent *event)
{

    if(!isDragging)
        return;

    double x = xAxis->pixelToCoord(event->pos().x());
    tracer->setGraph(this->graph(0));
    
    tracer->setGraphKey(x);
    tracer->updatePosition();
    double tracerX = tracer->position->key();
    double tracerY = tracer->position->value();
 
    textLableShow->setText(QString("频率：%1\n幅值：%2").arg(QString::number(tracerX,'f')).arg(tracerY));
    this->replot();

}

void MyCustomPlot::onMousePree(QMouseEvent *event)
{
    if(!isDragging)
        return;
    double x = xAxis->pixelToCoord(event->pos().x());
    tracer->setGraph(this->graph(0));
    tracer->setGraphKey(x);
    this->replot();

}

